package com.jarvis.du.baselibrary;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jarvis.du.baselibrary.util.LogUtil;
import com.jarvis.du.baselibrary.util.ToastUtil;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class CameraActivity extends Activity implements View.OnClickListener {
    public static final String imgPath = "/temple";
    private final String TEMPNAME = "tempName";
    private final int TAKE_PICTURE = 0;
    private final int CHOOSE_PICTURE = 1;
    private final int CROP = 2;
    private final int CROP_PICTURE = 3;
    private final int SCALE = 5;// 照片缩小比例
    boolean isCrop, isHidenAlbum;
    private Bitmap photo = null;
    private int hashCode;
    private String callback;
    private TextView take_photo, album, cancel;
    private LinearLayout llayout_dialog;
    private String active;
    private String path;// 文件路径
    private Activity activity;
    private View camera_line;
    private String sdPath;
    private String outPutImg;
    private File outFile;
    private SharedPreferences preferences;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        activity = this;
        // 禁止截屏
//		if (!BasicConstans.isScreenshot){
//			activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
//		}
        initView();
        initAction();
        initData();
        sdPath = getApplication().getExternalCacheDir() + "/image";
        File[] fileList = new File(sdPath).listFiles();
        if (fileList != null && fileList.length > 0) {
            for (File file : fileList) {
                file.delete();
            }
        }
        FileUtils.createDir(sdPath);
//        preferences = getApplication().getSharedPreferences("lalala",Context.MODE_PRIVATE);
        preferences = getPreferences(Context.MODE_PRIVATE);
    }

    protected void initView() {
        take_photo = (TextView) findViewById(R.id.take_photo);
        album = (TextView) findViewById(R.id.album);
        cancel = (TextView) findViewById(R.id.cancel);
        llayout_dialog = (LinearLayout) findViewById(R.id.llayout_dialog);
        camera_line = findViewById(R.id.camera_line);
    }

    protected void initAction() {
        take_photo.setOnClickListener(this);
        album.setOnClickListener(this);
        cancel.setOnClickListener(this);
        llayout_dialog.setOnClickListener(this);
    }

    protected void initData() {
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (!hasSDCard) {
            ToastUtil.showLong(activity, "未发现SD卡，请插入SD卡");
            finish();
            return;
        }
        isCrop = getIntent().getBooleanExtra("isCrop", true);
        isHidenAlbum = getIntent().getBooleanExtra("isHidenAlbum", false);
        hashCode = getIntent().getIntExtra("hashcode", 0);
        callback = getIntent().getStringExtra("callback");
        active = getIntent().getStringExtra("active");

        if (isHidenAlbum) {
            llayout_dialog.setVisibility(View.GONE);
            take_photo.performClick();
        }
    }

    /*
     * 保存图片
     */
    private String filePath(Bitmap photo) {
        String pictureDir = "";
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] byteArray = baos.toByteArray();
            String saveDir = Environment.getExternalStorageDirectory() + imgPath;
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdir();
            }
            String fileName = System.currentTimeMillis() + ".jpg";
            File file = new File(saveDir, fileName);
            file.delete();//?
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(byteArray);
            pictureDir = file.getPath();
            return pictureDir;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtils.close(baos);
            CloseUtils.close(bos);
            CloseUtils.close(fos);
        }
        return pictureDir;
    }

    /*
     * 截取图片（方形）
     */
    public void cropImage(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        // 实现对图片的裁剪,必须要设置图片的属性和大小
        // 设置属性，表示获取任意类型的图片
        if (Build.VERSION.SDK_INT >= 24) {
            String url = getPath(activity, uri);
            File file = new File(url);
            outPutImg = String.valueOf(System.currentTimeMillis()) + ".jpg";
            outFile = new File(sdPath + "/" + outPutImg);
            FileUtils.createFile(sdPath, outPutImg);
            Uri outputUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", outFile);
            Uri imageUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            intent.setDataAndType(imageUri, "image/*");

            List<ResolveInfo> resInfoList = activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                grantUriPermission(packageName, outputUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String url = getPath(activity, uri);
            intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
        } else {
            intent.setDataAndType(uri, "image/*");
        }
        // 设置可以滑动选选择区域的属性,注意这里是字符串"true"
        intent.putExtra("crop", "true");
        // 设置剪切框1:1比例的效果
        // 这个是裁剪时候的 裁剪框的 X方向的比例
        intent.putExtra("aspectX", 1);
        // 同上Y方向的比例. (注意： aspectX, aspectY ，两个值都需要为 整数，如果有一个为浮点数，就会导致比例失效)
        intent.putExtra("aspectY", 1);
        // 返回数据的时候的 X像素大小
        intent.putExtra("outputX", outputX);
        // 返回的时候 Y的像素大小
        intent.putExtra("outputY", outputY);
        intent.putExtra("outputFormat", "JPEG");
        // 是否去除面部检测， 如果你需要特定的比例去裁剪图片，那么这个一定要去掉，因为它会破坏掉特定的比例
        intent.putExtra("noFaceDetection", false);
        // 是否要返回值
        intent.putExtra("return-data", true);
        startActivityForResult(intent, requestCode);
    }

    // 原本uri返回的是file:///...来着的，android4.4返回的是content:///...
    @SuppressLint("NewApi")
    private String getPath(final Context context, final Uri uri) {
        if (uri == null) {
            return "";
        }
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String scheme = uri.getScheme();
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return sdPath + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } else if (scheme == null) {
            return uri.getPath();
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(scheme)) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(scheme)) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    private boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    private boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    private boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    private boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    private void choosePicture(Bitmap bitmap) {
//        bitmap = BitmapUtil.resetSize(bitmap, 30);
//        String baseStr = BitmapUtil.bitmapToBase64(bitmap);
//        EventBus.getDefault().post(new ChooseClickEvent(hashCode, callback, baseStr));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    path = sdPath + "/image.jpg";
                    Intent intent2 = new Intent();
                    intent2.putExtra("photoPath", path);
                    setResult(Activity.RESULT_OK, intent2);
                    finish();
                    break;

                case CHOOSE_PICTURE:
                    ContentResolver resolver = getContentResolver();
                    // 照片的原始资源地址
                    Uri originalUri = data.getData();
                    try {
                        // 使用ContentProvider通过URI获取原始图片
                        Bitmap photo = MediaStore.Images.Media.getBitmap(resolver, originalUri);
                        if (photo != null) {
//                            Bitmap smallBitmap;
//                            // 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
//                            smallBitmap = BitmapUtil.zoomBitmap(photo, photo.getWidth() / SCALE, photo.getHeight() / SCALE);
//                            photo.recycle();
//                            if (!TextUtils.isEmpty(active)) {
//                                if (active.equals("choosePicture")) {
//                                    choosePicture(smallBitmap);
//                                }
//                            }
                            path = sdPath + "/image.jpg";
                            BitmapUtil.saveBitmapToFile(path, photo);
                            photo.recycle();
                            photo = null;
                            String path = getPath(activity, originalUri);
                            // 释放原始图片占用的内存，防止out of memory异常发生
                            Intent intent = new Intent();
                            intent.putExtra("photoPath", path);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                            overridePendingTransition(R.anim.out_from_top, 0);
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;

                case CROP:
                    Uri uri = null;
                    if (data != null && data.getData() != null) {
                        uri = data.getData();
                        Log.i("TAG", "MainActivity_Data");
                    } else {
                        Log.i("TAG", "MainActivity_File");
                        String fileName = preferences.getString(TEMPNAME, "");
                        uri = Uri.fromFile(new File(sdPath, fileName));
                    }
                    // 改变裁剪图片长和宽
                    cropImage(uri, 300, 400, CROP_PICTURE);
                    break;

                case CROP_PICTURE:
                    if (Build.VERSION.SDK_INT >= 24) {
                        path = outFile.getPath();
                    } else {
                        photo = null;
                        Uri photoUri = data.getData();
                        if (photoUri != null) {
                            String path = photoUri.getPath();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                path = getPath(activity, photoUri);
                            }
                            photo = BitmapFactory.decodeFile(path);
                        }
                        if (photo == null) {
                            Bundle extra = data.getExtras();
                            if (extra != null) {
                                photo = (Bitmap) extra.get("data");
                                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                                photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                            }
                        }
                        path = filePath(photo);
                    }
                    Intent intent = new Intent();
                    intent.putExtra("photoPath", path);
                    setResult(Activity.RESULT_OK, intent);
                    photo = null;
                    Log.v("TAG", path);
                    finish();
                    break;
                default:
                    break;
            }
        } else {
            finish();//点击相册或拍照返回后直接finish掉这个页面
            //overridePendingTransition(R.anim.out_from_top, 0);
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(Activity.RESULT_CANCELED, null);
        finish();
    }

    /**
     * 返回true 表示可以使用  返回false表示不可以使用
     */
    public boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                return isCanUse;
            }
        }
        return isCanUse;
    }

    @Override
    public void onClick(View v) {
        int REQUEST_CODE;
        int i = v.getId();
        if (i == R.id.take_photo) {
            if (!cameraIsCanUse()) {
                ToastUtil.showLong(activity, "相机打开异常,确认是否拥有权限及相机是否可用");
                return;
            }
            Uri imageUri = null;
            String fileName = null;
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (isCrop) {
                REQUEST_CODE = CROP;
                // 删除上一次截图的临时文件
                String name = preferences.getString(TEMPNAME, "");
                BitmapUtil.deletePhotoAtPathAndName(sdPath, name);


                // 保存本次截图临时文件名字
                fileName = String.valueOf(System.currentTimeMillis()) + ".jpg";
                preferences.edit().putString(TEMPNAME, fileName).commit();
            } else {
                REQUEST_CODE = TAKE_PICTURE;
                fileName = "image.jpg";
            }

            // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
            if (Build.VERSION.SDK_INT >= 24) {
                File file = new File(sdPath, fileName);
                imageUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".fileprovider", file);
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                imageUri = Uri.fromFile(new File(sdPath, fileName));
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
            try {
                startActivityForResult(openCameraIntent, REQUEST_CODE);
            } catch (Exception e) {
                LogUtil.e("TAG", e.getMessage() + "");
                ToastUtil.showLong(activity, "相机打开异常,确认是否拥有权限及相机是否可用");
            }

        } else if (i == R.id.album) {
            Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
            if (isCrop) {
                REQUEST_CODE = CROP;
            } else {
                REQUEST_CODE = CHOOSE_PICTURE;
            }
            openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(openAlbumIntent, REQUEST_CODE);

        } else if (i == R.id.cancel) {
            finish();
            overridePendingTransition(R.anim.out_from_top, 0);

        } else if (i == R.id.llayout_dialog) {
            finish();
            overridePendingTransition(R.anim.out_from_top, 0);

        } else {
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
